<?php

namespace app\warehouse\logic;

use think\facade\Db;
use app\common\library\Excel;

class DetailedListInfoLogic extends BasicLogic
{

    /**
     * @desc   仓库清单
     * @author zhangheng
     * @date   2024-12-11
     */
    public function getList($params=[]){
        $limit              = getIsset($params,'limit',10);
        $sku                = getIsset($params,'seller_sku');
        $spu                = getIsset($params,'spu');
        $warehouse_position = getIsset($params,'warehouse_position');
        $create_time        = getIsset($params,'create_time');
        $update_time        = getIsset($params,'update_time');
        $where              = $order = [];

        if($sku){
            $where[] = ['seller_sku', 'like', '%' . $sku . '%'];
        }

        if($spu){
            $where[] = ['spu', '=', $spu];
        }

        if($warehouse_position){
            $where[] = ['warehouse_position', '=', $warehouse_position];
        }


        if ($create_time) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if ($update_time) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($update_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($update_time[1]) + 3600*24-1)];
        }

        if($spu){
            $where[] = ['spu', '=', $spu];
        }


        //排序
        $safe_quantity          = $params['safe_quantity'] ?? "";
        $on_way_quantity        = $params['on_way_quantity'] ?? "";
        $not_send_quantity      = $params['not_send_quantity'] ?? "";
        $using_quantity         = $params['using_quantity'] ?? "";
        $inventory_quantity     = $params['inventory_quantity'] ?? "";
        $all_inventory_quantity = $params['all_inventory_quantity'] ?? "";


        if($safe_quantity){
            $order['safe_quantity'] = $safe_quantity;
        }
        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }
        if($not_send_quantity){
            $order['not_send_quantity'] = $not_send_quantity;
        }
        if($using_quantity){
            $order['using_quantity'] = $using_quantity;
        }
        if($inventory_quantity){
            $order['inventory_quantity'] = $inventory_quantity;
        }
        if($all_inventory_quantity){
            $order['all_inventory_quantity'] = $all_inventory_quantity;
        }

        if(!$order){
            $order['update_time'] = 'desc';
            $order['spu']         = 'desc';
        }

        $res = Db::name('warehouse_sku_inventory')
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];

        //批量获取图片地址;
        $seller_skus = array_column($list,'seller_sku');
        $images      = Db::name('product_seller_sku')
                       ->field('id,seller_sku,image_info')
                       ->whereIn('seller_sku',$seller_skus)
                       ->select()
                       ->toArray();

        $images_map  = array_column($images,'image_info','seller_sku');
        foreach($list as $k=>$v){
            $iamge = $images_map[$v['seller_sku']]??'';
            $list[$k]['warehouse_position'] = $v['warehouse_position'] ?:'无货架位';
            $list[$k]['product_images']     = $v['product_images']?:$iamge;
        }

        //获取三个库存的总计
        $total_info = Db::name('warehouse_sku_inventory')
            ->where($where)
            ->field('id,on_way_quantity,not_send_quantity,using_quantity,inventory_quantity,all_inventory_quantity')
            ->select()
            ->toArray();

        $on_way_quantity_total        = array_sum(array_column($total_info, 'on_way_quantity'));
        $not_send_quantity_total      = array_sum(array_column($total_info, 'not_send_quantity'));
        $using_quantity_total         = array_sum(array_column($total_info, 'using_quantity'));
        $inventory_quantity_total     = array_sum(array_column($total_info, 'inventory_quantity'));
        $all_inventory_quantity_total = array_sum(array_column($total_info, 'all_inventory_quantity'));

        $data = [
            'list'                         => $list,
            'total'                        => $res->total(),
            'on_way_quantity_total'        => $on_way_quantity_total,
            'not_send_quantity_total'      => $not_send_quantity_total,
            'using_quantity_total'         => $using_quantity_total,
            'inventory_quantity_total'     => $inventory_quantity_total,
            'all_inventory_quantity_total' => $all_inventory_quantity_total,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    /**
     * @desc   仓库清单详情
     * @author zhangheng
     * @date   2024-12-11
     */
    public function find($params=[]){
        $id     = getIsset($params,'id');
        if(!$id) return   $this->jsonMessage(201,false,'ID不能为空!',null);
        $data    = Db::name('warehouse_sku_inventory')
            ->field("*")
            ->where('id',$id)
            ->find();
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    /**
     * @desc   仓库清单详情
     * @author zhangheng
     * @date   2024-12-11
     */
    public function delete($params=[]){
        $id     = getIsset($params,'id');
        if(!$id) return   $this->jsonMessage(201,false,'ID不能为空!',null);
        Db::name('warehouse_sku_inventory')->where('id',$id)->delete();
        return  $this->jsonMessage(200,true,'操作成功',null);
    }



    /**
     * @desc   仓库清单修改
     * @author zhangheng
     * @date   2024-12-11
     */
    public function edit($params=[]){
        $id                      = getIsset($params,'id');
        $all_inventory_quantity  = getIsset($params,'all_inventory_quantity');
        $product_name            = getIsset($params,'product_name');
        $product_images          = getIsset($params,'product_images');
        $remark                  = getIsset($params,'remark');
        if(!$id) return      $this->jsonMessage(201,false,'ID不能为空!',null);
        //获取原始的产品库存数;
        $old_inventory_quantity  = Db::name('warehouse_sku_inventory')->where(['id'=>$id])->value('all_inventory_quantity');
        Db::name('warehouse_sku_inventory')
            ->where(['id'=>$id])
            ->update(
                [
                    'remark'                 =>$remark,
                    'product_name'           =>$product_name,
                    'product_images'         =>$product_images,
                    'update_time'            =>date('Y-m-d H:i:s',time()),
         ]);
        if($old_inventory_quantity>$all_inventory_quantity){
            $number = ($old_inventory_quantity-$all_inventory_quantity);
            Db::name('warehouse_sku_inventory')
                    ->where(['id'=>$id])
                    ->dec('inventory_quantity', $number)
                    ->dec('all_inventory_quantity', $number)
                    ->update();
        }elseif($old_inventory_quantity < $all_inventory_quantity){
            $number = ($all_inventory_quantity - $old_inventory_quantity);
            Db::name('warehouse_sku_inventory')
                ->where(['id'=>$id])
                ->inc('inventory_quantity', $number)
                ->inc('all_inventory_quantity', $number)
                ->update();
        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }




    /**
     * @desc   仓库清单导出
     * @author zhangheng
     * @date   2024-12-11
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['SPU', 'spu'];
        $header[] = ['安全库存数量', 'safe_quantity'];
        $header[] = ['在途数量', 'on_way_quantity'];
        $header[] = ['未发数量', 'not_send_quantity'];
        $header[] = ['占用库存数量', 'using_quantity'];
        $header[] = ['可用库存数量', 'inventory_quantity'];
        $header[] = ['库存总数量', 'all_inventory_quantity'];
        $header[] = ['货架位', 'warehouse_position'];
        $header[] = ['创建时间', 'create_time'];
        $header[] = ['更新时间', 'update_time'];
        
        $spu             = getIsset($params,'spu');
        $where           = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
            $list = Db::name('warehouse_sku_inventory')
                ->where($where)
                ->order("id desc")
                ->select()->toArray();
        }else{
            $list = [];
        }

        $tableName = "DetailedListInfo";
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }


    /**
     * @desc   仓库清单spu导入
     * @author zhangheng
     * @date   2024-12-11
     */
    public function import($params = []){
        return  $this->jsonMessage(200,true,'操作成功',null);
    }



    /**
     * @desc   更换保存货架位
     * @author zhangheng
     * @date   2025-02-24
     */
    public function change_position($params = []){
         $id                  = $params['id']??'';
         $warehouse_position  = $params['warehouse_position']??'';
         Db::name('warehouse_sku_inventory')->where(['id'=>$id])->update([
             'warehouse_position'=>$warehouse_position,
             'update_time'       =>date('Y-m-d H:i:s',time()),
         ]);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }






}